#!/bin/bash

# yk

##########################################################################
# Linux environment
##########################################################################

if [[ "`uname -s`" == "Linux" ]]; then

	# timezone variable
	export TZ='Europe/Moscow'

	# locale settings
	export LANG="en_US.UTF-8"
	export LC_CTYPE="en_US.UTF-8"
	export LC_NUMERIC="en_US.UTF-8"
	export LC_TIME="en_US.UTF-8"
	export LC_COLLATE="en_US.UTF-8"
	export LC_MONETARY="en_US.UTF-8"
	export LC_MESSAGES="en_US.UTF-8"
	export LC_PAPER="en_US.UTF-8"
	export LC_NAME="en_US.UTF-8"
	export LC_ADDRESS="en_US.UTF-8"
	export LC_TELEPHONE="en_US.UTF-8"
	export LC_MEASUREMENT="en_US.UTF-8"
	export LC_IDENTIFICATION="en_US.UTF-8"
	export LC_ALL=

	# library path var
	export LIB_PATH_VAR=LD_LIBRARY_PATH

	# unix utils
	export BASH=/bin/bash
	export ECHO=/bin/echo
	export CAT=/bin/cat
	export CHMOD=/bin/chmod
	export CHOWN=/bin/chown
	export CP=/bin/cp
	export GAWK=/bin/gawk
	export AWK=/bin/awk
	export DATE=/bin/date
	export FIND=/usr/bin/find
	export GREP=/bin/grep
	export EGREP=/bin/egrep
	export GTAR=/bin/gtar
	export TAR=/bin/tar
	export ID=/usr/bin/id
	export KILL=/bin/kill
	export MKDIR=/bin/mkdir
	export MV=/bin/mv
	export PERL=/usr/bin/perl
	export PS=/bin/ps
	export RM=/bin/rm
	export RMDIR=/bin/rmdir
	export TAIL=/usr/bin/tail
	export HEAD=/usr/bin/head
	export TEE=/usr/bin/tee
	export TOUCH=/bin/touch
	export WHICH=/usr/bin/which
	export ID=/usr/bin/id
	export SPLIT=/usr/bin/split
	export SORT=/bin/sort
	export WC=/usr/bin/wc
	export XARGS=/usr/bin/xargs
	export SED=/bin/sed
	export MUTT=/usr/bin/mutt
	export DF=/bin/df
	export DU=/usr/bin/du
	export UNIQ=/usr/bin/uniq
	export DD=/bin/dd
	export UPTIME=/usr/bin/uptime
	export EXPR=/usr/bin/expr
	export CUT=/bin/cut
	export SSH=/usr/bin/ssh
	export SCP=/usr/bin/scp
	export RSYNC=/usr/bin/rsync
	export TR=/usr/bin/tr
	export MD5SUM=/usr/bin/md5sum
	export MKNOD=/bin/mknod
	export MKFIFO=/usr/bin/mkfifo
	export FINGER=/usr/bin/finger
	export BASENAME=/bin/basename
	export DIRNAME=/usr/bin/dirname
	export TEST=/usr/bin/test
	export T=$TEST
	export LS=/bin/ls
	export TRUE=/bin/true
	export FALSE=/bin/false
	export LOGGER=/usr/bin/logger
	export FILE=/usr/bin/file
	export GGZIP=/bin/gzip # dont use GZIP variable, (used by gzip)
	export GUNZIP=/bin/gunzip # dont use GZIP variable, (used by gzip)

##########################################################################
# AIX environment
##########################################################################
elif [[ "`uname -s`" == "AIX" ]]; then

	# timezone variable
	export TZ='WST-4'

	# locale
	export LANG="C"
	export LC_COLLATE="RU_RU.UTF-8"
	export LC_CTYPE="RU_RU.UTF-8"
	export LC_MONETARY="C"
	export LC_NUMERIC="C"
	export LC_TIME="C"
	export LC_MESSAGES="C"
	export LC_ALL=


	# library path var
	export LIB_PATH_VAR=LD_LIBRARY_PATH

	# unix utils
	export BASH=/opt/freeware/bin/bash
	export ECHO=/opt/freeware/bin/echo
	export CAT=/opt/freeware/bin/cat
	export CHMOD=/opt/freeware/bin/chmod
	export CHOWN=/opt/freeware/bin/chown
	export CP=/opt/freeware/bin/cp
	export GAWK=/opt/freeware/bin/gawk
	export AWK=/opt/freeware/bin/awk
	export DATE=/opt/freeware/bin/date
	export FIND=/opt/freeware/bin/find
	export GREP=/opt/freeware/bin/grep
	export EGREP=/opt/freeware/bin/egrep
	export TAR=/opt/freeware/bin/tar
	export ID=/opt/freeware/bin/id
	export KILL=/opt/freeware/bin/kill
	export MKDIR=/opt/freeware/bin/mkdir
	export MV=/opt/freeware/bin/mv
	export PERL=/usr/bin/perl
	export PS=/bin/ps
	export RM=/opt/freeware/bin/rm
	export RMDIR=/opt/freeware/bin/rmdir
	export TAIL=/opt/freeware/bin/tail
	export HEAD=/opt/freeware/bin/head
	export TEE=/opt/freeware/bin/tee
	export TOUCH=/opt/freeware/bin/touch
	export WHICH=/opt/freeware/bin/which
	export ID=/opt/freeware/bin/id
	export SPLIT=/opt/freeware/bin/split
	export SORT=/opt/freeware/bin/sort
	export WC=/opt/freeware/bin/wc
	export XARGS=/opt/freeware/bin/xargs
	export SED=/opt/freeware/bin/sed
	export MUTT=/opt/freeware/bin/mutt
	export DF=/opt/freeware/bin/df
	export DU=/opt/freeware/bin/du
	export UNIQ=/opt/freeware/bin/uniq
	export DD=/opt/freeware/bin/dd
	export UPTIME=/bin/uptime
	export EXPR=/opt/freeware/bin/expr
	export CUT=/opt/freeware/bin/cut
	export SSH=/bin/ssh
	export SCP=/bin/scp
	export RSYNC=/opt/freeware/bin/rsync
	export TR=/opt/freeware/bin/tr
	export MD5SUM=/bin/md5sum
    export MKNOD=/opt/freeware/bin/mknod
    export MKFIFO=/opt/freeware/bin/mkfifo
	export FINGER=/bin/finger
	export BASENAME=/opt/freeware/bin/basename
	export DIRNAME=/opt/freeware/bin/dirname
	export TEST=/opt/freeware/bin/test
	export T=$TEST
	export LS=/opt/freeware/bin/ls
	export TRUE=/opt/freeware/bin/true
	export FALSE=/opt/freeware/bin/false
	export LOGGER=/bin/logger
	export FILE=/bin/file
	export GGZIP=/opt/freeware/bin/gzip # dont use GZIP variable, (used by gzip)
	export GUNZIP=/opt/freeware/bin/gunzip # dont use GZIP variable, (used by gzip)
else
	echo "Error: environment for `uname -s` not defined, exiting"
	exit 1
fi


##########################################################################
# pipefail
##########################################################################
set -o pipefail

##########################################################################
# log, lock, tmp  variables for user scripts
##########################################################################
export LOG="/dev/null" # see enable_log function
export LOCK="$0".lock
export ME=`basename $0 2>/dev/null` 
export TMP_FILE1="/tmp/$ME.1.$$.$RANDOM$RANDOM$RANDOM.tmp"
export TMP_FILE2="/tmp/$ME.2.$$.$RANDOM$RANDOM$RANDOM.tmp"
export TMP_FILE3="/tmp/$ME.3.$$.$RANDOM$RANDOM$RANDOM.tmp"
export TMP_FILE4="/tmp/$ME.4.$$.$RANDOM$RANDOM$RANDOM.tmp"
export TMP_FILE5="/tmp/$ME.5.$$.$RANDOM$RANDOM$RANDOM.tmp"
export TMP_FILE6="/tmp/$ME.6.$$.$RANDOM$RANDOM$RANDOM.tmp"
export TMP_FILE7="/tmp/$ME.7.$$.$RANDOM$RANDOM$RANDOM.tmp"
export TMP_FILE8="/tmp/$ME.8.$$.$RANDOM$RANDOM$RANDOM.tmp"

export SSH_BATCH_OPTIONS="-o ConnectTimeout=60 -o ServerAliveInterval=1 -o ServerAliveCountMax=20 -o StrictHostKeyChecking=no -o BatchMode=yes"

export NLS_LANG="American_CIS.AL32UTF8"

export BUILD_ID="dontKillMe"
export ANT_OPTS="-Xmx1024m"

##########################################################################
# check environment
##########################################################################
cat <<EOF |
BASH
ECHO
CAT
CHMOD
CHOWN
CP
GAWK
AWK
DATE
FIND
GREP
EGREP
GTAR
TAR
ID
KILL
MKDIR
MV
PERL
PS
RM
RMDIR
TAIL
HEAD
TEE
TOUCH
WHICH
ID
SPLIT
SORT
WC
XARGS
SED
MUTT
DF
DU
UNIQ
DD
UPTIME
EXPR
CUT
SSH
SCP
RSYNC
TR
MD5SUM
MKNOD
MKFIFO
FINGER
BASENAME
DIRNAME
TEST
T
LS
TRUE
FALSE
FILE
LOGGER
GGZIP
GUNZIP
EOF
while read UTIL; do
	_PATH="`eval echo $\`echo $UTIL\``"
	if [ ! -x "$_PATH" ]; then
		echo "Can't find $UTIL at $_PATH"
		exit 1
	fi
done


##########################################################################
# bash functions. common for all 
##########################################################################

# PATH stuff
pathmunge() {
	if ! echo $PATH | $EGREP -q "(^|:)$1($|:)" ; then
		if [ "$2" = "after" ] ; then
			if [ -z "$PATH" ]; then 
				PATH=$1
			else
				PATH=$PATH:$1
			fi
		else
			if [ -z "$PATH" ]; then 
				PATH=$1
			else
				PATH=$1:$PATH
			fi
		fi
	fi
	export PATH
}

pathremove() {
	unset NEW_PATH
	for i in `echo $PATH|$AWK -F: 'BEGIN { RS=":" }; { print $1 }'`
	do
		if ! echo $i | $EGREP -q "(^|:)$1($|:)" ; then
			if [ -z "$NEW_PATH" ]; then 
				NEW_PATH=$i
			else
				NEW_PATH=$NEW_PATH:$i
			fi
		fi
	done
	PATH=$NEW_PATH
	export PATH
}

# LD_LIBRARY_PATH stuff
ldpathmunge() {
	if ! echo $LD_LIBRARY_PATH | $EGREP -q "(^|:)$1($|:)" ; then
		if [ "$2" = "after" ] ; then
			if [ -z "$LD_LIBRARY_PATH" ]; then 
				LD_LIBRARY_PATH=$1
			else
				LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$1
			fi
		else
			if [ -z "$LD_LIBRARY_PATH" ]; then 
				LD_LIBRARY_PATH=$1
			else
				LD_LIBRARY_PATH=$1:$LD_LIBRARY_PATH
			fi
		fi
	fi
	export LD_LIBRARY_PATH
}

ldpathremove() {
	unset NEW_LD_LIBRARY_PATH
	for i in `echo $LD_LIBRARY_PATH|$AWK -F: 'BEGIN { RS=":" }; { print $1 }'`
	do
		if ! echo $i | $EGREP -q "(^|:)$1($|:)" ; then
			if [ -z "$NEW_LD_LIBRARY_PATH" ]; then 
				NEW_LD_LIBRARY_PATH=$i
			else
				NEW_LD_LIBRARY_PATH=$i:$NEW_LD_LIBRARY_PATH
			fi
		fi
	done
	LD_LIBRARY_PATH=$NEW_LD_LIBRARY_PATH
	export LD_LIBRARY_PATH
}

# Java classpath manipulation
classpathmunge() {
	if ! echo $CLASSPATH | $EGREP -q "(^|:)$1($|:)" ; then
		if [ "$2" = "after" ] ; then
			CLASSPATH=$CLASSPATH:$1
		else
			CLASSPATH=$1:$CLASSPATH
		fi
	fi
	export CLASSPATH
}

classpathremove() {
	unset NEW_CLASSPATH
	for i in `echo $CLASSPATH|$AWK -F: 'BEGIN { RS=":" }; { print $1 }'`
	do
		if ! echo $i | $EGREP -q "(^|:)$1($|:)" ; then
		      NEW_CLASSPATH=$NEW_CLASSPATH:$i
		fi
	done
	CLASSPATH=${NEW_CLASSPATH}
	export CLASSPATH
}

# SQL path manipulation
sqlpathmunge() {
	if ! echo $SQLPATH | $EGREP -q "(^|:)$1($|:)" ; then
		if [ "$2" = "after" ] ; then
			SQLPATH=$SQLPATH:$1
		else
			if [ -z "$SQLPATH" ]; then 
				SQLPATH=$1
			else
				SQLPATH=$1:$SQLPATH
			fi
		fi
	fi
	export SQLPATH
}

sqlpathremove() {
	unset NEW_SQLPATH
	for i in `echo $SQLPATH|${AWK} -F: 'BEGIN { RS=":" }; { print $1 }'`
	do
		if ! echo $i | ${EGREP} -q "(^|:)$1($|:)" ; then
			if [ -z "$NEW_SQLPATH" ]; then 
				NEW_SQLPATH=$i
			else
				NEW_SQLPATH=$NEW_SQLPATH:$i
			fi
		fi
	done
	SQLPATH=$NEW_SQLPATH
	export SQLPATH
}

#_LIBPATH stuff
libpathmunge() {
	if ! echo $LIBPATH | $EGREP -q "(^|:)$1($|:)" ; then
		if [ "$2" = "after" ] ; then
			if [ -z "$LIBPATH" ]; then 
				LIBPATH=$1
			else
				LIBPATH=$LIBPATH:$1
			fi
		else
			if [ -z "$LIBPATH" ]; then 
				LIBPATH=$1
			else
				LIBPATH=$1:$LIBPATH
			fi
		fi
	fi
	export LIBPATH
}

libpathremove() {
	unset NEW_LIBPATH
	for i in `echo $LIBPATH|$AWK -F: 'BEGIN { RS=":" }; { print $1 }'`
	do
		if ! echo $i | $EGREP -q "(^|:)$1($|:)" ; then
			if [ -z "$NEW_LIBPATH" ]; then 
				NEW_LIBPATH=$i
			else
				NEW_LIBPATH=$i:$NEW_LIBPATH
			fi
		fi
	done
	LIBPATH=$NEW_LIBPATH
	export LIBPATH
}

enable_debug() {
	export DEBUG=1
}

enable_debug2() {
	export DEBUG=2
}

disable_debug() {
	unset DEBUG
}

msg() {
    local CUR_DATE=`date '+%Y-%m-%d %H:%M:%S'`
    #local MSG=`echo -e $1|tr '\n' ' '`
    local MSG=$1
    echo "$CUR_DATE $ME($$): $MSG" | $TEE -a $LOG
}   

enable_log() {
	# log variables for user scripts
	if [ -z "$1" ]; then
		LOG="$0"
		LOG="${0%.sh}.log"
		if [ "$LOG" == "-bash.log" ]; then
			LOG="/dev/null";
		else
			if echo $LOG|$GREP -q -E '^\.\/'; then
				LOG=`echo $LOG | $SED 's/^\.\///'`
				LOG="`pwd`/$LOG"
			fi
		fi
	else
		LOG="$1"
	fi
	
	if [ "$LOG" != "/dev/null" ]; then
		$TOUCH "$LOG" >/dev/null 2>&1 
		if [ ! -w "$LOG" ]; then
			echo "WARNING: cant open log for writing ($LOG), log: /dev/null"
			LOG="/dev/null"
		fi
	fi

	export LOG
	#msg "log file: $LOG"
}


debug() {
	if [ ! -z "$DEBUG" ]; then
		local CUR_DATE=`date '+%Y-%m-%d %H:%M:%S'`
		echo "$CUR_DATE $ME($$): $1" | $TEE -a "$LOG"
	fi
}

is_debug_enabled() {
	if [ -z "$DEBUG" ]; then
		return 1
	else
		return 0
	fi
}

debug2() {
	if [ "$DEBUG" == "2" ]; then
		local CUR_DATE=`date '+%Y-%m-%d %H:%M:%S'`
		echo "$CUR_DATE $ME($$): $1" | $TEE -a "$LOG"
	fi
}

warn() {
	local CUR_DATE=`date '+%Y-%m-%d %H:%M:%S'`
	echo "$CUR_DATE $ME($$): warning $1" | $TEE -a "$LOG"
}

cleanup()
{
	$RM -f "$TMP_FILE1" "$TMP_FILE2" "$TMP_FILE3" "$TMP_FILE4" "$TMP_FILE5" "$TMP_FILE6" "$TMP_FILE7" "$TMP_FILE8"
}

rm_lock_file()
{
	cleanup
	$RM -f "$LOCK"
}

die() {
	local CUR_DATE=`date '+%Y-%m-%d %H:%M:%S'`
	if [ -r  "$LOG" -a -w "$LOG" ]; then
		if [ "$LOG" == "/dev/null" ]; then
			echo "$CUR_DATE $ME($$): ERROR $1, exiting" 
		else
			echo "$CUR_DATE $ME($$): ERROR $1, exiting log:$LOG" | $TEE -a $LOG
		fi
	else
		echo "$CUR_DATE $ME($$): ERROR $1, exiting, log file \"$LOG\" not available or not writable" 
	fi
	rm_lock_file
	exit 1
}

is_ret_code_ok() {
	return $?
}

check_ret_code() {
	if [ "$?" != "0" ]; then
		die "$1"
	fi	
}

mail_msg() {
	local TO="$1"
	local SUBJECT="$2"
	local TEXT="$3"
	local ATTACHMENT="$4"


	if [ -r "$ATTACHMENT" ]; then
		msg "sending messsage to $TO with attachment: $ATTACHMENT"
		$ECHO -e "$TEXT" | ${MUTT} -s "$SUBJECT" -a "$ATTACHMENT" "$TO"
	else
		msg "sending messsage to $TO"
		$ECHO -e "$TEXT" | ${MUTT} -s "$SUBJECT" $TO
	fi
}

set_lock_file()
{
	if [ ! -z "$1" ]; then
		export LOCK="$1"	
	fi
	
	if ! ( set -o noclobber; echo "$$" > "$LOCK" ) 2> /dev/null; then
		msg "lockfile \"$LOCK\" exists (pid:$(cat $LOCK)), exiting";
		trap cleanup EXIT
		exit 1
	fi
}

sqlplus_query()
{
	local QUERY="$1"
	QUERY=`echo "$QUERY"|$PERL -pe 's/;\s*?$//'`;
	QUERY_OUT_TMP="/tmp/sqlplus_query.$RANDOM$RANDOM$RANDOM.tmp"
	$ORACLE_HOME/bin/sqlplus -s /nolog << EOFSQL >$QUERY_OUT_TMP
SET lin 32767
SET trimspool on
SET heading off
SET feedback off
SET verify off
SET timing off
SET term off
SET pages 0
connect $DB_USER_NAME/$DB_USER_PASSWORD@$ORACLE_SID
$QUERY;
exit
EOFSQL

	$CAT "$QUERY_OUT_TMP"|$PERL -pe 's/^\s+?(\S*)$/\1/g;'|$GREP -E -v '^$'
	$RM -f $QUERY_OUT_TMP
}

# trap ctrl-c and call ctrl_c()
if [[ "`$BASENAME -- $0`" != "-bash" ]] && [[ "`$BASENAME -- $0`" != "bash"  ]]; then
	trap cleanup_and_exit INT
	trap cleanup_and_exit TERM
	trap cleanup_and_exit QUIT
	trap cleanup_and_exit KILL
	trap cleanup_and_exit ABRT
	
	trap rm_lock_file EXIT
fi


cleanup_and_exit() {
	msg "INT,TERM,QUIT,KILL or ABRT signal, exiting"
	rm_lock_file
	trap $TRUE EXIT
	exit 1
}

msg_done() {
	local EXIT_CODE=$1
	
	local EXIT_CODE_STR=""
	local LOG_FILE_STR=""

	if [ ! -z "$EXIT_CODE" ]; then
		EXIT_CODE_STR=" ,exit code: $EXIT_CODE"
	fi

	if [ "$LOG" != "/dev/null" ]; then
		LOG_FILE_STR=", log:$LOG"
	fi
	
	msg "done (${SECONDS}s)$EXIT_CODE_STR$LOG_FILE_STR"
	rm_lock_file
}





# last line must be "true"
true



